package com.tc.groovy

/**
 * Created by cai.tian on 2018/1/18.
 */
class PropertyUtil {
    static boolean hasAdderMethod(Object obj, String name) {
        String addMethod = "add${upperCaseFirstLetter(name)}";
        return obj.metaClass.respondsTo(obj, addMethod);
    }

    static NestingType nestingType(Object obj, String name) {
        def decapitalizedName = BeanUtil.INSTANCE.toLowerCamelCase(name);
        if (obj.hasProperty(decapitalizedName)) {
            return NestingType.SINGLE;
        }
        if (hasAdderMethod(obj, name)) {
            return NestingType.AS_COLLECTION;
        }
        return NestingType.NA;
    }

    static void attach(NestingType nestingType, Object component, Object subComponent, String name) {
        switch (nestingType) {
            case NestingType.SINGLE:
                name = BeanUtil.INSTANCE.toLowerCamelCase(name);
                component."${name}" = subComponent;
                break;
            case NestingType.AS_COLLECTION:
                String firstUpperName = PropertyUtil.upperCaseFirstLetter(name)
                component."add${firstUpperName}"(subComponent);
                break;
        }
    }

    static String transformFirstLetter(String s, Closure closure) {
        if (s == null || s.length() == 0)
            return s;

        String firstLetter = new String(s.getAt(0));

        String modifiedFistLetter = closure(firstLetter);

        if (s.length() == 1)
            return modifiedFistLetter
        else
            return modifiedFistLetter + s.substring(1);

    }

    static String upperCaseFirstLetter(String s) {
        return transformFirstLetter(s, {String it -> it.toUpperCase()})
    }

}
